package DBCon;

import java.sql.*;

public class DBCon {
    private Connection con = null;
    private Statement st;
    private ResultSet rs;
    String url = "jdbc:mysql://localhost:3306/test?"+"serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";
    String user = "root";
    String password = "root";

//    连接数据库
    public Connection dbCon() {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (Exception e){
           e.printStackTrace();
        }
        try{
            con = DriverManager.getConnection(url,user,password);
        }catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

//    更新，添加，删除表数据
    public int query(String sql) {
        int rs = 0;
        con = dbCon();
        try {
            st = con.createStatement();
            rs = st.executeUpdate(sql);
        } catch (SQLException e) {
            close();
            e.printStackTrace();
        }

        return rs;
    }

//    获取表数据，获取结果集
    public ResultSet find(String sql) {
        try {
            con = dbCon();
            st = con.createStatement();
            rs = st.executeQuery(sql);
        } catch (SQLException e) {
            close();
            e.printStackTrace();
        }
        return rs;
    }


//    关闭数据库，断开连接
    public void close() {
        try {
            if (rs != null)
                rs.close();
            if (st != null)
                st.close();
            if (con != null)
                con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
